#include "audio_utils.h"
#include <sndfile.h>
#include <iostream>

namespace audio {
    bool load_audio(const std::string& filename) {
        // TODO: 实现音频加载
        (void)filename;  // 暂时消除警告
        return true;
    }

    bool save_audio(const std::string& filename) {
        // TODO: 实现音频保存
        (void)filename;  // 暂时消除警告
        return true;
    }
}

// 实现 AudioUtils 类的静态方法
std::pair<std::vector<float>, int> AudioUtils::load_audio(const std::string& path) {
    SF_INFO sfinfo;
    sfinfo.format = 0; // 重置格式
    
    SNDFILE* file = sf_open(path.c_str(), SFM_READ, &sfinfo);
    if (!file) {
        throw std::runtime_error("Error opening audio file: " + path + " - " + sf_strerror(file));
    }

    // 分配足够的空间来存储所有采样点
    std::vector<float> buffer(sfinfo.frames * sfinfo.channels);
    
    // 读取所有采样点
    sf_count_t count = sf_readf_float(file, buffer.data(), sfinfo.frames);
    if (count != sfinfo.frames) {
        sf_close(file);
        throw std::runtime_error("Error reading audio file: incomplete read");
    }

    // 如果是多声道，转换为单声道
    if (sfinfo.channels > 1) {
        std::vector<float> mono(sfinfo.frames);
        for (sf_count_t i = 0; i < sfinfo.frames; ++i) {
            float sum = 0.0f;
            for (int ch = 0; ch < sfinfo.channels; ++ch) {
                sum += buffer[i * sfinfo.channels + ch];
            }
            mono[i] = sum / sfinfo.channels;
        }
        buffer = std::move(mono);
    }

    sf_close(file);
    std::cout << "Loaded audio file: " << path << "\n"
              << "  Frames: " << sfinfo.frames << "\n"
              << "  Sample rate: " << sfinfo.samplerate << "\n"
              << "  Channels: " << sfinfo.channels << "\n";

    return {buffer, sfinfo.samplerate};
}

void AudioUtils::save_audio(
    const std::string& path,
    const std::vector<float>& data,
    int sample_rate
) {
    SF_INFO sfinfo;
    sfinfo.samplerate = sample_rate;
    sfinfo.channels = 1;  // 保存为单声道
    sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT;

    SNDFILE* file = sf_open(path.c_str(), SFM_WRITE, &sfinfo);
    if (!file) {
        throw std::runtime_error("Error creating audio file: " + path);
    }

    // 写入所有采样点
    sf_count_t count = sf_writef_float(file, data.data(), data.size());
    if (count != static_cast<sf_count_t>(data.size())) {
        sf_close(file);
        throw std::runtime_error("Error writing audio file: incomplete write");
    }

    sf_close(file);
    std::cout << "Saved audio file: " << path << "\n"
              << "  Frames: " << data.size() << "\n"
              << "  Sample rate: " << sample_rate << "\n";
} 